package xml;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class DeptParser {

	public static Dept parse(File file) throws ParserConfigurationException,
			SAXException, IOException {
		SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
		// 监听器dh提取数据并封装为Dept对象
		DeptHandler dh = new DeptHandler();
		parser.parse(file, dh);
		Dept d = dh.getDept();
		return d;

	}

	static class DeptHandler extends DefaultHandler {
		String xpath = "";

		Dept d = new Dept();

		Emp e;

		public Dept getDept() {
			return d;
		}

		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {
			xpath += "/" + qName;
			System.out.println(xpath);
			if ("/dept/emps/emp".equals(xpath)) {
				e = new Emp();
				d.getEmpList().add(e);
			} else if ("/dept".equals(xpath)) {
				d.setId(Integer.parseInt(attributes.getValue("id")));
				d.setEstablishtime(attributes.getValue("establishtime"));
			}
		}

		public void endElement(String uri, String localName, String qName)
				throws SAXException {
			xpath = xpath.substring(0, xpath.lastIndexOf("/"));
			System.out.println(xpath);
		}

		public void characters(char[] ch, int start, int length)
				throws SAXException {
			String s = new String(ch, start, length);
			if ("/dept/deptname".equals(xpath)) {
				d.setDeptname(s);
			} else if ("/dept/emps/emp/id".equals(xpath)) {
				e.setId(Integer.parseInt(s));
			} else if ("/dept/emps/emp/name".equals(xpath)) {
				e.setName(s);
			} else if ("/dept/emps/emp/salary".equals(xpath)) {
				e.setSalary(Double.parseDouble(s));
			} else if ("/dept/mgr".equals(xpath)) {
				d.setMgr(s);
			}
		}
	}

	public static void main(String[] args) throws ParserConfigurationException,
			SAXException, IOException {
		Dept d = parse(new File("/home/tarena/0hean/hean/src/xml/dept.xml"));
		System.out.println(d);
		for (Iterator it = d.getEmpList().iterator(); it.hasNext();) {
			Emp e = (Emp) it.next();
			System.out.println(e);
		}
	}
}
